/**
 * 插件下载页面交互功能
 * 基于Element UI风格和Google设计标准
 */

(function() {
    'use strict';

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        initFAQ();
        initDownloadTracking();
        initVideoButtons();
        initBackupDownloads();
        initPrivacyModal();
        initScrollAnimations();
        initSmoothScroll();
        
        // 检查是否需要自动弹出隐私政策
        checkAutoShowPrivacy();
    });

    /**
     * 初始化FAQ折叠功能
     */
    function initFAQ() {
        const faqItems = document.querySelectorAll('.faq-item');
        
        faqItems.forEach(item => {
            const question = item.querySelector('.faq-question');
            
            question.addEventListener('click', function() {
                // 关闭其他打开的FAQ
                faqItems.forEach(otherItem => {
                    if (otherItem !== item) {
                        otherItem.classList.remove('active');
                    }
                });
                
                // 切换当前FAQ
                item.classList.toggle('active');
            });
        });
    }

    /**
     * 初始化下载跟踪
     */
    function initDownloadTracking() {
        const downloadBtn = document.getElementById('downloadBtn');
        
        if (downloadBtn) {
            downloadBtn.addEventListener('click', function(e) {
                // 添加下载动画效果
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = '';
                }, 150);
                
                // 跟踪下载事件（可以发送到分析服务）
                trackDownload();
                
                // 显示下载提示
                showDownloadNotification();
            });
        }
    }

    /**
     * 初始化视频按钮
     */
    function initVideoButtons() {
        const installVideoBtn = document.getElementById('installVideoBtn');
        const usageVideoBtn = document.getElementById('usageVideoBtn');
        
        // 安装教程视频按钮
        if (installVideoBtn) {
            installVideoBtn.addEventListener('click', function(e) {
                e.preventDefault();
                // 这里可以设置实际的B站视频链接
                const videoUrl = 'https://www.bilibili.com/list/3493283001011095/?sid=4968594&spm_id_from=333.1387.0.0&oid=115269942908946&bvid=BV1k8ngzNEtL'; // 临时链接，需要替换为实际视频链接
                window.open(videoUrl, '_blank');
                
                // 跟踪视频点击事件
                trackVideoClick('install');
            });
        }
        
        // 使用教程视频按钮
        if (usageVideoBtn) {
            usageVideoBtn.addEventListener('click', function(e) {
                e.preventDefault();
                // 这里可以设置实际的B站视频链接
                const videoUrl = 'https://space.bilibili.com/3493283001011095/lists'; // 临时链接，需要替换为实际视频链接
                window.open(videoUrl, '_blank');
                
                // 跟踪视频点击事件
                trackVideoClick('usage');
            });
        }
    }

    /**
     * 跟踪视频点击事件
     */
    function trackVideoClick(type) {
        console.log(`Video clicked: ${type}`);
        
        // 这里可以发送到分析服务
        if (typeof gtag !== 'undefined') {
            gtag('event', 'video_click', {
                'event_category': 'extension',
                'event_label': type
            });
        }
    }

    /**
     * 初始化备用下载链接
     */
    function initBackupDownloads() {
        const backupLink = document.querySelector('.backup-link');
        
        if (backupLink) {
            backupLink.addEventListener('click', function(e) {
                // 跟踪备用下载事件
                trackBackupDownload('淘宝快捷助手.zip');
                
                // 显示下载提示
                showBackupDownloadNotification('淘宝快捷助手.zip');
            });
        }
    }

    /**
     * 跟踪备用下载事件
     */
    function trackBackupDownload(fileName) {
        console.log(`Backup download: ${fileName}`);
        
        // 这里可以发送到分析服务
        if (typeof gtag !== 'undefined') {
            gtag('event', 'backup_download', {
                'event_category': 'extension',
                'event_label': fileName
            });
        }
    }

    /**
     * 显示备用下载通知
     */
    function showBackupDownloadNotification(fileName) {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = 'backup-download-notification';
        notification.innerHTML = `
            <div class="notification-content">
                <i class="icon-download"></i>
                <span>正在下载 ${fileName}</span>
            </div>
        `;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #67C23A, #85CE61);
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
            z-index: 1000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        `;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    /**
     * 初始化隐私政策弹出层
     */
    function initPrivacyModal() {
        const privacyLink = document.getElementById('privacyLink');
        const privacyModal = document.getElementById('privacyModal');
        const privacyClose = document.getElementById('privacyClose');
        const privacyAccept = document.getElementById('privacyAccept');
        const privacyOverlay = document.querySelector('.privacy-overlay');

        // 打开弹出层
        if (privacyLink) {
            privacyLink.addEventListener('click', function(e) {
                e.preventDefault();
                showPrivacyModal();
            });
        }

        // 关闭弹出层
        if (privacyClose) {
            privacyClose.addEventListener('click', function() {
                hidePrivacyModal();
            });
        }

        // 点击遮罩层关闭
        if (privacyOverlay) {
            privacyOverlay.addEventListener('click', function() {
                hidePrivacyModal();
            });
        }

        // 同意按钮
        if (privacyAccept) {
            privacyAccept.addEventListener('click', function() {
                hidePrivacyModal();
                // 可以在这里添加同意后的逻辑
                console.log('用户已同意隐私政策');
            });
        }

        // ESC键关闭
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && privacyModal && privacyModal.classList.contains('show')) {
                hidePrivacyModal();
            }
        });
    }

    /**
     * 显示隐私政策弹出层
     */
    function showPrivacyModal() {
        const privacyModal = document.getElementById('privacyModal');
        if (privacyModal) {
            privacyModal.classList.add('show');
            document.body.style.overflow = 'hidden'; // 禁止背景滚动
        }
    }

    /**
     * 隐藏隐私政策弹出层
     */
    function hidePrivacyModal() {
        const privacyModal = document.getElementById('privacyModal');
        if (privacyModal) {
            privacyModal.classList.remove('show');
            document.body.style.overflow = ''; // 恢复背景滚动
        }
    }

    /**
     * 检查是否需要自动弹出隐私政策
     */
    function checkAutoShowPrivacy() {
        // 检查全局变量 isShowPricy
        if (typeof isShowPricy !== 'undefined' && isShowPricy === 1) {
            // 延迟一点时间显示，确保页面完全加载
            setTimeout(() => {
                showPrivacyModal();
            }, 500);
        }
    }

    /**
     * 跟踪下载事件
     */
    function trackDownload() {
        // 这里可以添加分析代码，比如Google Analytics
        console.log('Extension download initiated');
        
        // 示例：发送到分析服务
        if (typeof gtag !== 'undefined') {
            gtag('event', 'download', {
                'event_category': 'extension',
                'event_label': 'google-taobao-extension'
            });
        }
    }

    /**
     * 显示下载通知
     */
    function showDownloadNotification() {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = 'download-notification';
        notification.innerHTML = `
            <div class="notification-content">
                <i class="icon-download"></i>
                <span>下载已开始，请检查浏览器下载文件夹</span>
            </div>
        `;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #67C23A, #85CE61);
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
            z-index: 1000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        `;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }

    /**
     * 初始化滚动动画
     */
    function initScrollAnimations() {
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, observerOptions);

        // 观察需要动画的元素
        const animatedElements = document.querySelectorAll('.feature-card, .step-item, .usage-card, .faq-item');
        animatedElements.forEach(el => {
            el.style.opacity = '0';
            el.style.transform = 'translateY(30px)';
            el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            observer.observe(el);
        });
    }

    /**
     * 初始化平滑滚动
     */
    function initSmoothScroll() {
        // 为所有内部链接添加平滑滚动
        const internalLinks = document.querySelectorAll('a[href^="#"]');
        
        internalLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                
                const targetId = this.getAttribute('href').substring(1);
                const targetElement = document.getElementById(targetId);
                
                if (targetElement) {
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    }

    /**
     * 复制到剪贴板功能
     */
    function copyToClipboard(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(() => {
                showCopyNotification();
            });
        } else {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            showCopyNotification();
        }
    }

    /**
     * 显示复制通知
     */
    function showCopyNotification() {
        const notification = document.createElement('div');
        notification.className = 'copy-notification';
        notification.textContent = '已复制到剪贴板';
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #409EFF;
            color: white;
            padding: 10px 15px;
            border-radius: 4px;
            z-index: 1000;
            font-size: 14px;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.opacity = '1';
        }, 100);
        
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 2000);
    }

    /**
     * 检测浏览器兼容性
     */
    function checkBrowserCompatibility() {
        const userAgent = navigator.userAgent;
        const isChrome = /Chrome/.test(userAgent) && /Google Inc/.test(navigator.vendor);
        const isEdge = /Edg/.test(userAgent);
        
        if (!isChrome && !isEdge) {
            showBrowserWarning();
        }
    }

    /**
     * 显示浏览器警告
     */
    function showBrowserWarning() {
        const warning = document.createElement('div');
        warning.className = 'browser-warning';
        warning.innerHTML = `
            <div class="warning-content">
                <i class="icon-warning"></i>
                <span>建议使用Chrome浏览器以获得最佳体验</span>
                <button class="warning-close">&times;</button>
            </div>
        `;
        
        warning.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: #E6A23C;
            color: white;
            padding: 10px 20px;
            text-align: center;
            z-index: 1001;
            font-size: 14px;
            transform: translateY(-100%);
            transition: transform 0.3s ease;
        `;
        
        document.body.appendChild(warning);
        
        setTimeout(() => {
            warning.style.transform = 'translateY(0)';
        }, 1000);
        
        // 关闭按钮事件
        const closeBtn = warning.querySelector('.warning-close');
        closeBtn.addEventListener('click', () => {
            warning.style.transform = 'translateY(-100%)';
            setTimeout(() => {
                if (warning.parentNode) {
                    warning.parentNode.removeChild(warning);
                }
            }, 300);
        });
    }

    /**
     * 页面性能监控
     */
    function initPerformanceMonitoring() {
        // 监控页面加载时间
        window.addEventListener('load', () => {
            const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart;
            console.log(`页面加载时间: ${loadTime}ms`);
        });
    }

    /**
     * 错误处理
     */
    function initErrorHandling() {
        window.addEventListener('error', (event) => {
            console.error('页面错误:', event.error);
            // 这里可以发送错误报告到服务器
        });
    }

    // 初始化所有功能
    checkBrowserCompatibility();
    initPerformanceMonitoring();
    initErrorHandling();

    // 导出公共方法（如果需要）
    window.ExtensionDownload = {
        copyToClipboard,
        showDownloadNotification,
        trackDownload
    };

})();
